<!-- metalSalesDetailPage.vue -->
<template>
  <!-- 在页面顶部或底部添加加载遮罩 -->
  <div v-loading="submitting" class="sales-contract-detail-container">
    <div class="sales-contract-detail-container">
      <!-- Document Information Group -->
      <el-card class="info-card" shadow="never">
        <template #header>
          <div class="card-header">
            <div class="title-wrapper">
              <span class="title-text">单据信息</span>
              <span v-if="multiStoreMode" class="store-name">{{ salesContract.storeName }}</span>
            </div>
            <!-- Action Buttons -->
            <div class="action-buttons" v-if="!this.editMode">
              <el-button plain @click="handleCopy">
                <el-icon>
                  <CopyDocument />
                </el-icon> 复制
              </el-button>
              <el-button plain @click="handlePrint" style="margin-right: 20px">
                <el-icon>
                  <Printer />
                </el-icon> 打印
              </el-button>
              <el-button v-if="SalesContract.hasMetalOrderEditPermission()" type="primary" plain @click="handleEdit">
                <el-icon>
                  <Edit />
                </el-icon> 编辑
              </el-button>
              <el-button v-if="SalesContract.hasMetalOrderEditPermission()" type="danger" plain @click="handleDelete">
                <el-icon>
                  <Delete />
                </el-icon> 删除
              </el-button>
            </div>
          </div>
        </template>
        <el-form ref="ruleFormRef" :model="formData" label-width="100px">
          <el-row :gutter="20">
            <el-col v-if="!this.editMode" :span="6">
              <input-widget-web v-model="formData.docCode" label="单据编号" prop="docCode" :readonly="!this.editMode" />
            </el-col>
            <el-col :span="6">
              <partner-select v-model="formData.targetObject" label="客户" prop="targetObject" :readonly="!this.editMode"
                initialPartnerType="all" :targetObjectPlatformType="TargetObjectPlatformType.TUserCreated"
                :rules="[{ required: true, message: '请选择客户', trigger: 'blur' }]" :basicUiAction="basicUiAction"
                @update:model-value="val => { updateTargetObject(val); }" />
            </el-col>
            <el-col v-if="supportMultyWarehouse" :span="6">
              <warehouse-select v-model="formData.warehouse" label="仓库" prop="warehouse" :readonly="!this.editMode"
                :inventoryUiAction="inventoryUiAction" />
            </el-col>
            <el-col :span="6">
              <date-time-select v-model="formData.operateDate" label="销售日期" prop="operateDate"
                :readonly="!this.editMode" type="datetime" />
            </el-col>
            <el-col :span="6">
              <employee-select v-model="formData.operator" label="经办人" prop="operator" :readonly="!this.editMode"
                :enterpriseMgtUiAction="enterpriseMgtUiAction" />
            </el-col>
          </el-row>
        </el-form>
        <el-table :data="salesContract.commmodityList" style="width: 100%" @selection-change="handleSelectionChange"
          :class="{ 'edit-mode-spacing': editMode }">
          <!-- 勾选列 -->
          <el-table-column type="selection" width="55" v-if="editMode" />
          <el-table-column label="品名" width="180">
            <template #default="scope">
              <SubcommoditySelect :model-value="scope.row.commodity" :commodityUiActionProps="commodityUiAction"
                :readonly="!editMode" :filter-props="metalSubcommodityFilter" @update:model-value="val => {
                  // 设置商品
                  scope.row.commodity = val;
                }" />
            </template>
          </el-table-column>
          <el-table-column label="重量" align="center" width="120">
            <template #default="scope">
              <input-cell v-if="scope.row.commodity" :readonly="!editMode" :model-value="scope.row.count.value"
                :numberMode="true" :precision="countPrecision" @update:model-value="val => {
                  scope.row.setCount(new CsDouble(val, countPrecision));
                  salesContract.calculatePriceAndQuantity();
                }" />
            </template>
          </el-table-column>

          <el-table-column label="折后重量" align="center" width="120">
            <template #header>
              <span>折后重量</span>
              <el-tooltip content="" placement="top" raw-content>
                <el-icon style="margin-left: 5px; cursor: pointer;">
                  <QuestionFilled />
                </el-icon>
              </el-tooltip>
            </template>
            <template #default="scope">
              <template
                v-if="scope.row.commodity && scope.row.metalSalesTradeMode?.code === MetalSalesTradeMode.SettleMetal.code">
                <input-cell v-if="scope.row.commodity" :readonly="true"
                  :model-value="scope.row.countAfterDiscount.value" :numberMode="true" :precision="countPrecision"
                  @update:model-value="val => { scope.row.setCountAfterDiscount(new CsDouble(val, countPrecision)); purchaseContract.calculatePriceAndQuantity(); }" />
              </template>
            </template>
          </el-table-column>

          <el-table-column label="单价(元/g)" align="center" width="120">
            <template #default="scope">
              <template v-if="scope.row.metalSalesTradeMode?.code === MetalSalesTradeMode.SettleMetal.code">
                <!-- Read-only mode -->
                <span>--</span>
              </template>
              <template v-else>
                <input-cell v-if="scope.row.commodity" :readonly="!editMode"
                  :model-value="scope.row.singlePriceAfterTax.value" :numberMode="true" :precision="fundPrecision"
                  @update:model-value="val => {
                    scope.row.setSinglePriceAfterTax(new CsFundDouble(val, fundPrecision));
                    salesContract.calculatePriceAndQuantity();
                  }" />
              </template>
            </template>
          </el-table-column>
          <el-table-column label="应收金额" align="center" width="120">
            <template #default="scope">
              <template v-if="scope.row.metalSalesTradeMode?.code === MetalSalesTradeMode.SettleMetal.code">
                <!-- Read-only mode -->
                <span>--</span>
              </template>
              <template v-else>
                <input-cell :readonly="true" :model-value="scope.row.batchPriceWithTax.value" :numberMode="true"
                  :precision="fundPrecision" @update:model-value="val => {
                    scope.row.setBatchPriceWithTax(new CsFundDouble(val, fundPrecision));
                    salesContract.calculatePriceAndQuantity();
                  }" />
              </template>
            </template>
          </el-table-column>
          <el-table-column label="模式" align="center" width="150">
            <template #header>
              <span>模式</span>
              <el-tooltip :content="tradeModeHint" placement="top" raw-content>
                <el-icon style="margin-left: 5px; cursor: pointer;">
                  <QuestionFilled />
                </el-icon>
              </el-tooltip>
            </template>
            <template #default="scope">
              <template v-if="!editMode">
                <!-- Read-only mode -->
                <span v-if="scope.row.metalSalesTradeMode">
                  {{ scope.row.metalSalesTradeMode.name }}
                </span>
              </template>
              <template v-else>
                <!-- Edit mode -->
                <el-select v-if="scope.row.commodity" :model-value="scope.row.metalSalesTradeMode?.code"
                  placeholder="请选择模式" @change="val => {
                    handleModeSelect(scope.row, val);
                  }" style="width: 100%">
                  <el-option v-for="mode in metalSalesTradeModes" :key="mode.code" :label="mode.name"
                    :value="mode.code">
                  </el-option>
                </el-select>
              </template>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" v-if="editMode">
            <template #default="scope">
              <el-button link size="small" @click="handleDeleteRow(scope.row)" style="color: #f56c6c;">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="amount-section" :class="{ 'edit-mode-spacing': editMode }">
          <!-- Other Fees 编辑模式 on the left -->
          <div v-if="editMode" style="width: 560px;">
            <div class="amount-item other-fees-left">
              <span class="label right-align">其他费用:</span>
              <div class="value left-align">
                <input-cell :width="'200px'" :readonlyWidth="'200px'" :readonly="true"
                  :model-value="salesContract.otherFundsMorePrice.value.value" :numberMode="true"
                  :precision="fundPrecision" />
                <el-button v-if="editMode" style="margin-left: 8px;" type="primary" size="small" class="rounding-button"
                  @click="handleSelectOtherFeeType(salesContract.otherFundsMorePrice)">
                  添加
                </el-button>
              </div>
            </div>

            <!-- Detailed other fees list -->
            <div v-if="salesContract.otherFundsMorePrice.length > 0" class="other-fees-detail">
              <div :class="{ 'readonly-mode': !editMode }">
                <div v-for="(fee, index) in salesContract.otherFundsMorePrice.otherFeeList" :key="index"
                  class="other-fee-item">
                  <span class="fee-name">{{ fee.otherFeeType.name }}:</span>
                  <input-cell :width="'220px'" :readonly="!editMode" :model-value="fee.fundDouble.value"
                    :numberMode="true" :precision="fundPrecision" @update:model-value="val => {
                      fee.fundDouble = new CsFundDouble(val, fundPrecision);
                      salesContract.calculatePriceAndQuantity();
                    }">
                    <el-button link size="small" @click="handleDeleteOtherFeeRowMore(fee)" style="color: #f56c6c;">
                      删除
                    </el-button>
                  </input-cell>
                </div>
              </div>
            </div>
          </div>

          <!-- Other Fees 只读模式 on the left -->
          <div v-if="!editMode" style="width: 560px;">
            <div class="value left-align">
              <span>商品金额:{{ salesContract.commodityPrice.value + "; " }}</span>
              <span v-if="salesContract.otherFundsMorePrice.length > 0">{{
                salesContract.otherFundsMorePrice.getOtherFeeString() }}</span>
            </div>
          </div>

          <!-- Total section on the right -->
          <div class="total-section">
            <div class="amount-summary-row">
              <span class="label right-align" style="font-size: 16px; font-weight: bold; color: #606266;">合计:</span>

              <div v-if="salesContract.hasSettledMetal" class="amount-summary-item">
                <span class="value left-align">{{ salesContract.getSettledMetalInfo() }}</span>
              </div>

              <div class="amount-summary-items">
                <div v-if="salesContract.totalMount.value != 0" class="amount-summary-item">
                  <span class="label right-align">应收款:</span>
                  <span class="value left-align">{{ formatCurrency(salesContract.totalMount.value) }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div v-if="!editMode" class="remark-container">
          <div class="remark-label">备注:</div>
          <div class="remark-content">{{ salesContract.remark || '-' }}</div>
        </div>
        <div v-if="editMode" class="remark-section-edit">
          <div class="separator-line"></div>
          <input-widget-web class="value left-align" v-model="formData.remark" label="备注" prop="remark"
            placeholder="请输入备注信息" :remarkMode="true" :inputFrameWidth="'100%'" />
        </div>
      </el-card>

      <!-- 底部操作栏 (仅在编辑模式下显示) -->
      <bottom-bar :visible="editMode">
        <template #left>
          <span class="doc-maker-info">制单人: {{ docMakerBottmBar }}</span>
        </template>
        <template #right>
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
        </template>
      </bottom-bar>

      <!-- 商品选择弹窗 -->
      <subcommodity-select-dialog ref="commoditySelectDialog" :basic-ui-action="basicUiAction"
        @select="handleCommoditySelect" />

      <!-- 其他费用选择弹窗 -->
      <other-fee-type-select-dialog ref="otherFeeTypeSelectDialog" :fund-ui-action="fundUiAction"
        @select="handleOtherFeeTypeSelect" />

      <order-result-dialog ref="orderResultDialog" />
    </div>
  </div>
</template>

<script>
import { SalesContract } from '../../public/engine/sales/salesContract'
import { CommodityBatchWithTax } from '../../public/engine/sales/sales'
import { Employee } from '../../public/engine/enterpriseMgt/employee'
import { CsDouble } from '../../public/engine/common/csDouble'
import { CsFundDouble } from '../../public/engine/common/csFundDouble'
import { CommonOrderStatus } from '../../public/engine/common/docDefinition'
import { SalesUiAction } from '../../public/engine/uiAction/salesUiAction'
import { InventoryUiAction } from '../../public/engine/uiAction/inventoryUiAction'
import { Util } from '../../public/utils/util'
import { DateUtil } from '../../public/utils/dateUtil'
import { Engine } from '../../public/engine/engine'
import { ElMessage, ElMessageBox } from 'element-plus'
import { BasicUiAction } from '../../public/engine/uiAction/basicUiAction'
import { EnterpriseMgtUiAction } from '../../public/engine/uiAction/enterpriseMgtUiAction.js'
import { ActionResult, ActionResultType } from '../../public/engine/common/actionResult.js'
import InputWidgetWeb from '../../public/views/componentsWeb/InputWidgetWeb.vue'
import PartnerSelect from '../../public/views/componentsWeb/PartnerSelect.vue'
import WarehouseSelect from '../../public/views/componentsWeb/WarehouseSelect.vue'
import DateTimeSelect from '../../public/views/componentsWeb/DateTimeSelect.vue'
import EmployeeSelect from '../../public/views/componentsWeb/EmployeeSelect.vue'
import QualityInputCell from '../../public/views/componentsWeb/QualityInputCell.vue'
import ValueCheckboxWidget from '../../public/views/componentsWeb/ValueCheckboxWidget.vue'
import InputCell from '../../public/views/componentsWeb/InputCell.vue'
import SubcommoditySelectDialog from '../../views/inventory/subcommoditySelectDialog.vue'
import BottomBar from '../../public/views/componentsWeb/BottomBar.vue'
import EventBus from '../../public/engine/ipc/eventBus'
import TabUtil from '@/plugins/tab'
import { MessageUtil } from '@/utils/MessageUtil'
import { Definition } from '../../public/engine/common/definition.js'
import FundAccountSelect from '../../public/views/componentsWeb/FundAccountSelect.vue'
import { FundUiAction } from '../../public/engine/uiAction/fundUiAction'
import { OtherFundDouble } from '../../public/engine/funds/otherFundDouble'
import { MetalSalesTradeMode } from '../../public/engine/common/metalDefinition.js'
import OtherFeeTypeSelectDialog from '../fund/otherFeeTypeSelectDialog.vue'
import { TargetObjectPlatformType } from '../../public/engine/targetOrg/targetObject'
import orderResultDialog from '../dialog/orderResultDialog.vue'
import { TestSimulateData } from '../../public/engine/testMgr/testSimulateData'
import SubcommoditySelect from '../../public/views/componentsWeb/SubcommoditySelect.vue'
import { CommodityUiAction } from '../../public/engine/uiAction/commodityUiAction.js'
import { SubCommodityFilter, SubCommodityMetalFilterTypeEnum } from '../../public/engine/commodity/subCommodity'
import MetalFinessInputCell from '../../public/views/componentsWeb/MetalFinessInputCell.vue'

export default {
  name: 'metalSaleOrder',
  components: {
    InputWidgetWeb,
    PartnerSelect,
    WarehouseSelect,
    DateTimeSelect,
    EmployeeSelect,
    QualityInputCell,
    InputCell,
    SubcommoditySelectDialog,
    BottomBar,
    ValueCheckboxWidget,
    FundAccountSelect,
    OtherFeeTypeSelectDialog,
    orderResultDialog,
    SubcommoditySelect,
    MetalFinessInputCell
  },

  data() {
    return {
      salesContract: SalesContract.empty({
        operator: Engine.profile?.nickName,
        operatorId: Engine.profile?.id
      }),
      orgSalesContract: SalesContract.empty({
        operator: Engine.profile?.nickName,
        operatorId: Engine.profile?.id
      }),
      basicUiAction: new BasicUiAction(),
      salesUiAction: new SalesUiAction(),
      inventoryUiAction: new InventoryUiAction(),
      enterpriseMgtUiAction: new EnterpriseMgtUiAction(),
      loading: false,
      CommonOrderStatus,
      SalesContract,
      CsDouble,
      CsFundDouble,
      editMode: false,
      orderId: "",
      formData: {
        docCode: '',
        title: '',
        targetObject: null,
        warehouse: null,
        operateDate: null,
        operator: null,
        remark: '',
        updator: null,
        docMaker: null,
      },
      // 返回数据
      retValue: null,
      selectedCommodities: [],
      submitting: false, // 添加提交状态标识
      fundUiAction: new FundUiAction(),
      MetalSalesTradeMode,
      TargetObjectPlatformType,
      commodityUiAction: new CommodityUiAction(),
      metalSubcommodityFilter: new SubCommodityFilter({ metalType: SubCommodityMetalFilterTypeEnum.MetalRelatedOnly }),
    }
  },

  mounted() {
    this.retValue = null;
    this.orderId = (this.$route.params.id || this.$route.query.id) || "";

    if (!Util.isEmpty(this.orderId)) {
      this.loadSalesContractData();
    } else {
      this.editMode = true;
      this.syncFormData();
      this.fillWithEmptyCommodityLineData();
    }
  },
  beforeUnmount() {
    if (this.retValue) {
      EventBus.emit('salesContractUpdated', null);
      this.retValue = null;
    }
  },

  deactivated() {
    if (this.retValue) {
      EventBus.emit('salesContractUpdated', null)
      this.retValue = null;
    }
  },

  computed: {
    // 模式提示
    tradeModeHint() {
      return "1 付金结价: 影响客户存欠款，商户资金账户，应收款，24K贵金属库存, 贵金属账户<br>" +
        "  1) 按设24K成色对应单价结算应收金额 <br>" +
        "  2) 影响客户存欠款: 客户存欠款 = 客户存欠款 - 本单合计剩余应收款 <br>" +
        "  3) 按重量产生24K贵金属出库，以及扣除24K贵金属账户余额 <br>" +
        "<br>" +
        "2 付金: 影响客户存欠料，24K贵金属库存, 贵金属账户<br>" +
        "  1) 客户存欠料 = 客户存欠料 - 本次交易重量<br>" +
        "  2) 按交易重量产生24K贵金属出库，以及扣除24K贵金属账户余额 <br>" +
        "<br>" +
        "3 结价: 影响客户存欠款、存欠料，商户资金账户，应收款<br>" +
        "  1) 影响客户存欠款: 客户存欠款 = 客户存欠款 - 本单合计剩余应收款 <br>" +
        "  2) 客户存欠料 = 客户存欠料 + 折后重量 <br>" +
        "  3) 注意: 需要核对是否有旧料销售场景"
    },

    multiStoreMode() {
      return Engine.getOrgSettings().multiStoreMode;
    },
    metalSalesTradeModes() {
      return [MetalSalesTradeMode.SettleMetal_SettlePrice, MetalSalesTradeMode.SettleMetal, MetalSalesTradeMode.SettledPrice];
    },
    latestUpdateInfo() {
      return (this.salesContract.updateor && this.salesContract.updateDate) ?
        (this.salesContract.updateor + "  " + DateUtil.getDayTitle(this.salesContract.updateDate)) : null;
    },

    docMaker() {
      return (this.salesContract.id && this.salesContract.docMaker && this.salesContract.recordDate) ?
        (this.salesContract.docMaker + "  " + DateUtil.getDayTitle(this.salesContract.recordDate)) : null
    },

    docMakerBottmBar() {
      return Engine.profile?.nickName.isEmpty
        ? Engine.profile?.userName
        : Engine.profile?.nickName;
    },

    countPrecision() {
      return Definition.precision;
    },

    fundPrecision() {
      return Definition.fundPrecision;
    },

    disCountRation() {
      return Definition.gConstDiscountRatePrecision;
    },

    preOffsetText() {
      return this.editMode ? "余额:" + Util.getFundString(this.salesContract.customerPreRecieveAmount - this.salesContract.preReceiveOffset.value)
        : this.formatCurrency(this.salesContract.preReceiveOffset.value, true);
    },

    supportMultyWarehouse() {
      return Engine.getOrgSettings().enableMultiWarehouse;
    },

    // 有付款金额时显示
    // 正数数才是往来商户对单位欠款，用于扣除付款
    showPreReceiveHexiao() {
      console.log("metalSalesDetailPage, this.salesContract.totalMount.value:" + this.salesContract.totalMount.value +
        "; this.salesContract.customerPreRecieveAmount:" + this.salesContract.customerPreRecieveAmount +
        ";this.salesContract.preReceiveOffset.value:" + this.salesContract.preReceiveOffset.value);

      if (this.salesContract.totalMount.value > 0 &&
        (this.salesContract.customerPreRecieveAmount > 0 || (this.salesContract.preReceiveOffset.value > 0))) {
        return true;
      }

      return false;
    },
  },

  methods: {
    // 更新供应商
    updateTargetObject(val) {
      this.salesContract.targetObject = val;
    },

    // 填充空的商品信息
    fillWithEmptyCommodityLineData() {
      // 如果商品记录数量小于 4，添加空记录达到 4条
      if (this.salesContract.commmodityList.length < 4) {
        for (let i = this.salesContract.commmodityList.length; i < 4; i++) {
          this.salesContract.addCommodityBatch(CommodityBatchWithTax.empty());
        }
      } else {
        // 如果商品数量大于4，判断最后一个商品是否是空记录，如果是的，添加一条空记录
        if (this.salesContract.commmodityList[this.salesContract.commmodityList.length - 1].commodity == null) {
          this.salesContract.addCommodityBatch(CommodityBatchWithTax.empty());
        }
      }
    },
    handleModeSelect(batch, val) {
      console.log("Batch updated:", batch, val);
      batch.metalSalesTradeMode = MetalSalesTradeMode.fromCode(val);
      this.salesContract.calculatePriceAndQuantity();
    },
    syncFormData() {
      this.formData = {
        docCode: this.salesContract.docCode,
        title: this.salesContract.title,
        targetObject: this.salesContract.targetObject,
        warehouse: this.salesContract.wareHouse,
        operateDate: this.salesContract.operateDate,
        operator: new Employee({ id: this.salesContract.operatorId, name: this.salesContract.operator }),
        remark: this.salesContract.remark,
        updator: (this.salesContract.updateor && this.salesContract.updateDate) ?
          (this.salesContract.updateor + "  " + DateUtil.getDayTitle(this.salesContract.updateDate)) : null,
        docMaker: (this.salesContract.id && this.salesContract.docMaker && this.salesContract.recordDate) ?
          (this.salesContract.docMaker + "  " + DateUtil.getDayTitle(this.salesContract.recordDate)) : null,
      };
    },

    fillWithFormData() {
      this.salesContract.title = this.formData.title;
      this.salesContract.targetObject = this.formData.targetObject;
      this.salesContract.wareHouse = this.formData.warehouse;

      // formData.operateDate 控件变更日期会转换为字符串，这里需要转换回Date对象
      if (!(this.formData.operateDate instanceof Date)) {
        this.salesContract.operateDate = DateUtil.strToDate(this.formData.operateDate);
      } else {
        this.salesContract.operateDate = this.formData.operateDate;
      }

      this.salesContract.setOperator({
        operator: this.formData.operator.name,
        operatorId: this.formData.operator.id
      });
      this.salesContract.remark = this.formData.remark;
    },

    handleDeleteRow(row) {
      this.salesContract.removeCommodityBatch(row);
      // ElMessage.success('商品已删除');
    },
    // 抹零
    handleRounding() {
      this.salesContract.setDiscountValueWithSmallChange();
    },

    // 商品选择 items 类型 SubCommodityInventorySumData
    handleCommoditySelect(items) {
      if (items && items.length > 0) {
        for (let commodity of items) {
          let exists = false;

          if (!exists) {
            let batch = new CommodityBatchWithTax({
              commodity: commodity.subCommodity,
              count: new CsDouble(1),
              availableCount: commodity.availableCount,
              inventoryCount: commodity.totalInventoryCount,
              batchPrice: commodity.subCommodity.retailPrice,
              singlePrice: commodity.subCommodity.retailPrice,
              referPrice: commodity.subCommodity.retailPrice,
              metalSalesTradeMode: MetalSalesTradeMode.SettleMetal_SettlePrice,
            });

            if (this.salesContract.isSupportDetailWithTax) {
              this.salesContract.addCommodityBatch(batch);
            } else {
              this.salesContract.addCommodityBatch(CommodityBatchWithTax.fromCommodityBatchWithTaxSimpleMode(
                batch));
            }
          } else {
            ElMessage.warning(`商品[${commodity.subCommodity.name}]已存在`);
          }
        }
      }
    },

    // 其他类型费用选择
    handleOtherFeeTypeSelect(items, otherFeePrice) {
      console.log('handleOtherFeeTypeSelect', items);

      for (let i = 0; i < items.length; i++) {
        otherFeePrice.addOtherFeeFundAccount(new OtherFundDouble(items[i], CsFundDouble.zero()));
      }
    },

    handleCopy() {
      this.salesContract.resetForCopy();
      this.editMode = true;
      MessageUtil.showSuccessMsg("复制完成");
    },

    handlePrint() {
      // Create a new window/tab for printing
      const printWindow = window.open('', '_blank');

      // Generate HTML content for printing
      const printContent = this.generatePrintContent();

      // Write content to the new window
      printWindow.document.write(printContent);
      printWindow.document.close();
    },

    handleEdit() {
      this.editMode = true;
    },

    async handleDelete() {
      if (Util.isEmpty(this.salesContract.id)) {
        TabUtil.closePage();
      } else {
        try {
          await ElMessageBox.confirm("确定要删除该销售单据吗？", "删除确认", {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          });

          this.submitting = true;

          let delResult = await this.salesUiAction.removeSalesOrder({
            orderId: this.salesContract.id,
            docType: this.salesContract.docType
          });

          if (delResult == null) {
            this.retValue = new ActionResult({ type: ActionResultType.Del });
            MessageUtil.showSuccessMsg("删除成功");
            TabUtil.closePage();
          }
        } catch (error) {
          if (error !== 'cancel') {
            console.error("salesContractDetailPage handleDelete error:", error);
            ElMessage.error("删除操作失败");
          }
        } finally {
          this.submitting = false;
        }
      }
    },

    handleAddCommodity() {
      if (this.formData.warehouse == null ||
        this.formData.warehouse.id == null ||
        Util.isEmpty(this.formData.warehouse.id)) {
        MessageUtil.showWarningMsg("请先选择仓库");
        return;
      }

      this.$refs.commoditySelectDialog.open(
        this.salesContract.commmodityList.map(item => ({
          commodity: item.commodity
        })),
        {
          warehouse: this.formData.warehouse
        }
      );
    },

    // 添加其他费用
    handleSelectOtherFeeType(otherPrice) {
      this.$refs.otherFeeTypeSelectDialog.open([], otherPrice);
    },

    // 删除其他费用项
    handleDeleteOtherFeeRowLess(item) {
      this.salesContract.otherFundsLessPrice.removeOtherFeeFundAccount(item);
      this.salesContract.calculatePriceAndQuantity();
    },

    // 删除其他费用项
    handleDeleteOtherFeeRowMore(item) {
      this.salesContract.otherFundsMorePrice.removeOtherFeeFundAccount(item);
      this.salesContract.calculatePriceAndQuantity();
    },

    handleSelectionChange(selection) {
      this.selectedCommodities = selection;
    },

    handleDeleteSelectedCommodities() {
      if (this.selectedCommodities.length === 0) {
        ElMessage.warning('请至少选择一个商品进行删除');
        return;
      }

      // 删除选中的商品
      this.selectedCommodities.forEach(commodity => {
        this.salesContract.removeCommodityBatch(commodity);
      });

      // 清空选中
      this.selectedCommodities = [];
    },

    // 取消编辑
    handleCancel() {
      this.salesContract = SalesContract.clone(this.orgSalesContract);
      this.editMode = false;
    },

    async handleSubmit() {
      try {
        // First validate the form
        await this.$refs.ruleFormRef.validate();
        // 验证表单
        const validationError = this.salesContract.validateOrder();
        if (validationError) {
          if (validationError.errorMsg) {
            if (validationError.msgBoxConfirm) {
              try {
                await ElMessageBox.confirm(
                  validationError.errorMsg,
                  '信息错误',
                  {
                    confirmButtonText: '确认',
                    type: 'error'
                  }
                );

                // 错误信息直接返回
                return;
              } catch (confirmError) {
                // User cancelled
                this.submitting = false;
                return;
              }
            }
            else {
              ElMessage.error(validationError.errorMsg);
              return;
            }
          }
          else if (validationError.warningMsg) {
            if (validationError.msgBoxConfirm) {
              try {
                await ElMessageBox.confirm(
                  validationError.warningMsg,
                  '确认提交',
                  {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning'
                  }
                );
              } catch (confirmError) {
                // User cancelled
                this.submitting = false;
                return;
              }
            }
            else {
              ElMessage.error("validationError.errorMsg");
              return;
            }
          }
        }

        this.submitting = true;
        this.fillWithFormData();
        const orderResult = await this.salesUiAction.updateOrCreateSalesContract(this.salesContract, true);

        if (orderResult) {
          if (Util.isEmpty(this.salesContract.id)) {
            this.retValue = new ActionResult({ type: ActionResultType.New });
          } else {
            this.retValue = new ActionResult({ type: ActionResultType.UpdateCommon });
          }
        }

        if (orderResult) {
          // 刷新订单页面
          ElMessage.success("提交保存成功");
          this.orderId = orderResult.id;
          this.editMode = false;
          this.loadSalesContractData();

          // 显示结果
          //this.$refs.orderResultDialog.open(orderResult);
        }
      } catch (error) {
        console.error('保存失败', error);
        ElMessage.error("保存失败");
      } finally {
        this.submitting = false;
      }
    },

    async loadSalesContractData() {
      try {
        this.loading = true;
        const res = await this.salesUiAction.getSalesDetailInfo(this.orderId);

        if (res) {
          this.salesContract = res;
          this.orgSalesContract = SalesContract.clone(res);
          this.salesContract.orderBeforeEdit = this.orgSalesContract;
          this.syncFormData();
          this.fillWithEmptyCommodityLineData();
        } else {
          ElMessage.error('获取销售单详情失败');
        }
      } catch (error) {
        console.error('加载销售单数据失败:', error);
        ElMessage.error('加载销售单数据失败');
      } finally {
        this.loading = false;
      }
    },

    formatCount(value, withSignal = false) {
      return Util.getCountString(value, null, { withPrePositiveNegtiveSignal: withSignal });
    },

    formatCurrency(value, readOnlyZeroDashLine = false) {
      return Util.getFundString(value, { zeroDashLine: readOnlyZeroDashLine && !this.editMode });
    },
    formateDate(date) {
      return DateUtil.formatDate(date, 'yyyy-MM-dd HH:mm');
    },
    // In methods section of metalSalesDetailPage.vue
    generatePrintContent() {
      // Create a printable version of the sales contract details
      return `
<!DOCTYPE html>
<html>
<head>
  <title>销售单据 - ${this.salesContract.docCode}</title>
  <style>
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    body {
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
        color: #333;
        line-height: 1.6;
        padding: 20px;
        min-height: 100vh;
    }

    .container {
        max-width: 1000px;
        margin: 20px auto;
        background: white;
        padding: 30px;
        border-radius: 12px;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
        position: relative;
    }

    .header {
        margin-bottom: 25px;
        border-bottom: 1px solid #bec5cc;
        padding-bottom: 15px;
    }

    .header-row {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 2px;
    }

    .company-name {
        font-size: 22px;
        font-weight: bold;
        color: #2c3e50;
        flex: 1;
    }

    .document-title {
        text-align: center;
        font-size: 28px;
        font-weight: bold;
        color: #2c3e50;
        flex: 2;
    }

    .document-code {
        text-align: right;
        font-size: 16px;
        color: #2c3e50;
        flex: 1;
    }

    .info-row {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .department {
        font-size: 16px;
        flex: 1;
    }

    .customer-info {
        text-align: center;
        font-size: 16px;
        flex: 2;
    }

    .date {
        text-align: right;
        font-size: 16px;
        flex: 1;
    }

    .info-table {
        width: 100%;
        border-collapse: collapse;
        margin-bottom: 25px;
    }

    .info-table td {
        padding: 12px;
        border: 1px solid #ddd;
    }

    .items-table {
        width: 100%;
        border-collapse: collapse;
        margin-bottom: 5px;
        box-shadow: 0 2px 2px rgba(0, 0, 0, 0.1);
    }

    .items-table th,
    .items-table td {
        border: 1px solid #ddd;
        padding: 2px;
        text-align: center;
    }

    .items-table th {       
        font-weight: 600;
    }

    .items-table tr:nth-child(even) {
        background-color: #f9f9f9;
    }

    .items-table tr:hover {
        background-color: #f1f9ff;
    }

    .summary-inline {
        display: flex;
        justify-content: flex-end;
        gap: 20px;
        margin-bottom: 5px;
        padding: 5px;
        border-radius: 5px;
    }

    .summary-item .label {
        font-weight: 600;
        margin-right: 5px;
    }

    .summary-item .minLabel {
        font-weight: 500;
        margin-right: 5px;
    }

    .summary-item .value.total {
        color: #2c3e50;
        font-weight: bold;
    }

    @media (max-width: 768px) {
        .summary-inline {
            flex-direction: column;
            align-items: flex-end;
        }
    }

    .text-right {
        text-align: right;
        font-weight: 600;
    }

    .total-row {
        background-color: #eaf7ff;
        font-weight: bold;
    }

    .remark-section {
        padding: 5px;
        border-top: 1px solid #bec5cc;
        border-bottom: 1px solid #bec5cc;
    }

    .footer-section {
        display: flex;
        justify-content: space-between;
        margin-top: 5px;
        border-bottom: 1px solid #bec5cc;
    }

    .declaration {
        flex: 2;
        padding: 5px 15px 15px 15px;
        border-radius: 8px;
        font-size: 14px;
    }

    .declaration-title {
        display: inline;
        font-size: 14px;
    }

    .declaration-content {
        margin-top: 1px;
        margin-left: 20px;
        line-height: 1.1;
        font-size: 14px;
    }

    .declaration-line {
        display: flex;
        margin-bottom: 2px;
        font-size: 14px;
    }

    .declaration-number {
        min-width: 15px;
        font-weight: 500;
        font-size: 14px;
    }

    .qr-code {
        flex: 1;
        text-align: center;
        padding: 2px;
    }

    .qr-code img {
        width: 100px;
        height: 100px;
        border: 1px solid #ddd;
        border-radius: 5px;
    }

    .qr-code p {
        margin-top: 0px;
        font-size: 12px;
        color: #666;
    }

    .address-info {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 0px;
        padding: 0px 0;
    }

    .address-text {
        font-size: 14px;
        font-weight: 500;
    }

    .contact-name {
        font-size: 14px;
    }

    .additional-info {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 0px;
        padding: 0px 0;
        font-size: 13px;
    }

    .website {
        flex: 1;
        text-align: left;
    }

    .customer-id {
        flex: 1;
        text-align: center;
    }

    .phone {
        flex: 1;
        text-align: right;
    }

    .footer-operator {
        display: flex;
        justify-content: center;
        margin-top: 10px;
        padding: 0px 0;            
    }

    .document-info {
        display: flex;
        justify-content: space-between;
        width: 100%;           
        align-items: center;
        font-size: 14px;
    }

    .document-info span {
        flex: 1;
        text-align: center;
        padding: 0 10px;
        white-space: nowrap;
    }

    .btn {
        padding: 12px 25px;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        font-weight: 600;
        transition: all 0.3s ease;
    }

    .btn-print {
        background: linear-gradient(to right, #2c3e50, #4a6491);
        color: white;
    }

    .btn-print:hover {
        background: linear-gradient(to right, #1a2530, #3a5078);
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
    }

    .btn-download {
        background: linear-gradient(to right, #3498db, #2c3e50);
        color: white;
    }

    .btn-download:hover {
        background: linear-gradient(to right, #2980b9, #1a2530);
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
    }

    .button-group {
        display: flex;
        justify-content: center;
        gap: 15px;
        margin-top: 10px;
    }

    @media print {
        body {
            background-color: white;
            padding: 0;
        }

        .container {
            box-shadow: none;
            padding: 5px 15px 5px 15px;
        }

        .btn-print {
            display: none !important;
        }
    }

    @media (max-width: 768px) {
        .header-row,
        .info-row {
            flex-direction: column;
            text-align: center;
            gap: 10px;
        }

        .company-name,
        .document-title,
        .document-code,
        .department,
        .customer-info,
        .date {
            text-align: center;
            width: 100%;
        }

        .summary-table {
            width: 100%;
        }

        .document-title {
            font-size: 24px;
            order: -1;
        }

        .footer-section {
            flex-direction: column;
        }

        .qr-code {
            margin-top: 0px;
            order: 2;
        }

        .additional-info {
            flex-direction: column;
            gap: 5px;
            text-align: center;
        }

        .website,
        .customer-id,
        .phone {
            text-align: center;
            width: 100%;
        }

        .document-info {
            flex-direction: column;
            gap: 8px;
        }

        .document-info span {
            width: 100%;
            text-align: center;
        }

        .button-group {
            margin-top: 15px;
        }
    }
  </style>
</head>
<body>
  <div class="container">
    <button class="btn btn-print" onclick="window.print()" style="position: absolute; top: 30px; right: -100px; z-index: 100;">打印</button>
    <div class="header">
      <!-- 第一行：公司名称 - 标题 - 单据编号 -->
      <div class="header-row">
        <div class="department">深圳市恒泰珠宝有限公司</div>
        <div class="document-title">合记结算单</div>
        <div class="document-code">单号: ${this.salesContract.docCode}</div>
      </div>

      <!-- 第二行：部门 - 客户信息 - 日期 -->
      <div class="info-row">
        <div class="department">部门: 揭阳</div>
        <div class="customer-info">客户名称: ${this.salesContract.targetObject?.name || ''}</div>
        <div class="date">日期: ${this.formateDate(this.salesContract.operateDate)}</div>
      </div>
    </div>
    
    <table class="items-table">
      <thead>
        <tr>
          <th>序号</th>
          <th>品名</th>         
          <th>重量(g)</th>
          <th>成色</th>
          <th>折后重量(g)</th>
          <th>单价(元/g)</th>
          <th>应收金额(元)</th>
        </tr>
      </thead>
      <tbody>
        ${this.salesContract.commmodityList.map((item, index) => `
        <tr>
          <td>${index + 1}</td>
          <td>${item.commodity?.standard || ''}</td>
          <td>${item.commodity == null ? "" : item.count?.value.toFixed(2) || '0.00'}</td>
          <td>${item.commodity == null ? "" : (item.discount?.value == 100 ? "24K" : (item.discount?.value || 0) * 10)}</td>
          <td>${(item.commodity == null ||
          item.metalSalesTradeMode?.code === MetalSalesTradeMode.SettledPrice.code
        )
          ? "" : item.countAfterDiscount?.value.toFixed(2) || '0.00'}</td>
          <td>${item.commodity == null || item.metalSalesTradeMode?.code === MetalSalesTradeMode.SettleMetal.code ? "" : item.singlePriceAfterTax?.value.toFixed(2) || '--'}</td>
          <td>${item.commodity == null || item.metalSalesTradeMode?.code === MetalSalesTradeMode.SettleMetal.code ? "" : item.batchPriceWithTax?.value.toFixed(2) || '--'}</td>
        </tr>
        `).join('')}
      </tbody>
    </table>

    <div class="summary-inline">
      <div class="summary-item">
        <span class="minLabel">商品金额:</span>
        <span class="value">${this.formatCurrency(this.salesContract.commodityPriceWithTax?.value)}</span>
      </div>

    ${this.salesContract.otherFundsMorePrice && this.salesContract.otherFundsMorePrice.otherFeeList && this.salesContract.otherFundsMorePrice.otherFeeList.length > 0 ?
          this.salesContract.otherFundsMorePrice.otherFeeList.map(fee => `
        <div class="summary-item">
          <span class="minLabel">${fee.otherFeeType?.name || '其他费用'}:</span>
          <span class="value">${this.formatCurrency(fee.fundDouble?.value || 0)}</span>
        </div>
        `).join('') : ''}

      ${(this.salesContract.discount?.value !== 0) ? `
      <div class="summary-item">
        <span class="minLabel">抹零:</span>
        <span class="value">${this.formatCurrency(this.salesContract.discount?.value)}</span>
      </div>
      ` : ''}
      
      ${(this.salesContract.preReceiveOffset?.value !== 0) ? `
      <div class="summary-item">
        <span class="minLabel">余额抵扣:</span>
        <span class="value">${this.formatCurrency(this.salesContract.preReceiveOffset?.value)}</span>
      </div>
      ` : ''}
      <div class="summary-item">
        <span class="label">合计:</span>
         <span class="value total">${this.salesContract.getSettledMetalInfo()}</span>
        <span class="value total">${this.formatCurrency(this.salesContract.totalMount.value)}</span>
      </div>
    </div>

    <div class="remark-section">
      <p><strong>备注:</strong> ${this.salesContract.remark || ''}</p>
    </div>

    <div class="footer-section">
      <div class="declaration">
        <p>
          <span class="declaration-title">声明:</span>
          <span>1. 以上货品价格以上海交易所实时价格参考为标准;</span>
        </p>
        <div class="declaration-content">
          <div class="declaration-line">
            <span class="declaration-number"></span>
            <span>2. 客户承诺以上物品物料款项是合理合法所有;</span>
          </div>
          <div class="declaration-line">
            <span class="declaration-number"></span>
            <span>3. 此单据是双方认同有效的凭证。</span>
          </div>
        </div>

        <div class="address-info">
          <span class="address-text">地址: 揭阳市揭东区富经桥恒富花园8栋15</span>
          <span class="contact-name">联系人: 郭先生</span>
        </div>

        <div class="additional-info">
          <div class="website">行情网站: www.hjzb999.com</div>
          <div class="customer-id">客户信息: </div>
          <div class="phone">联系电话: 18688068055</div>
        </div>
      </div>

      <div class="qr-code">
        <img src="https://api.qrserver.com/v1/create-qr-code/?size=120x120&data=https://www.example.com" alt="二维码">
      </div>
    </div>

    <div class="footer-operator">
      <div class="document-info">
        <span>制单: ${this.salesContract.docMaker || ''}</span>
        <span>复核: ${this.salesContract.operator || ''}</span>
        <span>联系电话: 1333333333</span>
        <span>顾客签名: ___________</span>
      </div>
    </div>
  </div>
</body>
</html>`
    },
  }
}
</script>

<style scoped>
.sales-contract-detail-container {
  padding: 16px;
  padding-bottom: 80px;
  /* 留出bottom bar的空间 */
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.action-buttons {
  display: flex;
  gap: 12px;
  margin-bottom: 0px;
  padding: 0 16px;
}

.title-wrapper {
  display: flex;
  align-items: center;
  gap: 12px;
}

.summary-container {
  flex: 1;
  min-width: 300px;
  display: flex;
  align-items: center;
  gap: 12px;
}

.total-info {
  color: #606266;
  font-size: 14px;
  white-space: nowrap;
}

.store-name {
  font-size: 12px;
  color: #606266;
}

.title-text {
  font-size: 16px;
  font-weight: bold;
}

.status-tag {
  margin-left: 12px;
}

.commodity-image {
  width: 40px;
  height: 40px;
  margin-right: 12px;
}

.remark-content {
  white-space: pre-wrap;
  word-break: break-all;
}

.info-card {
  margin-bottom: 16px;
  border-radius: 8px;
  width: 1200px;
  /* Fixed width */
  margin-left: 0;
  margin-right: auto;
}

.info-card,
.items-card,
.amount-summary-card,
.other-info-card {
  margin-bottom: 16px;
  border-radius: 8px;
}

.amount-item {
  display: flex;
  align-items: center;
}

.amount-item .label.right-align {
  text-align: right;
  flex: 0 0 100px;
  /* Fixed width for labels */
  color: #606266;
  margin-right: 12px;
  font-size: 13px;
}

.amount-item .value {
  font-weight: bold;
}

.total-amount .value {
  color: #E64D4D;
  font-size: 16px;
}

.other-fees-detail {
  flex-direction: column;
  align-items: flex-start;
}

.other-fees-list {
  width: 100%;
  margin-top: 0px;
  padding-top: 0px;
  /* border-top: 1px solid #ebeef5; */
}

.readonly-mode .other-fees-list {
  width: 400px;
}

.other-fee-item {
  display: flex;
  justify-content: space-between;
  width: 100%;
  padding: 4px 0;
  padding-left: 110px;
  font-size: 12px;
}

.fee-name {
  width: 50px;
  color: #606266;
}

.fee-value {
  font-weight: bold;
  color: #333;
}

.amount-section {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  flex-wrap: wrap;
  gap: 16px;
  margin: 16px 0;
}

.amount-section.edit-mode-spacing {
  margin-top: 30px;
}

.other-fees-left {
  display: flex;
  align-items: center;
  flex: 1;
  min-width: 300px;
}

.other-fees-detail {
  flex: 1 100%;
  margin-top: 8px;
}

.total-section {
  flex: 1;
  min-width: 300px;
  display: flex;
}

.total-main {
  display: flex;
  align-items: center;
  gap: 16px;
}

.total-items-container {
  display: flex;
  gap: 16px;
  align-items: center;
}

.total-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.amount-summary-row {
  display: flex;
  align-items: center;
  gap: 16px;
  justify-content: flex-end;
}

.amount-summary-items {
  display: flex;
  align-items: center;
  gap: 16px;
}

.amount-summary-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.remark-container {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  margin: 0px 0;
  padding: 0px 0;
}

.remark-label {
  font-weight: bold;
  color: #606266;
  white-space: nowrap;
  font-size: 12px;
}

.remark-content {
  white-space: pre-wrap;
  word-break: break-all;
  flex: 1;
  color: #606266;
  font-size: 12px;
}

.remark-section-edit {
  margin-top: 2px;
}

.separator-line {
  height: 1px;
  background-color: #ebeef5;
  margin-bottom: 10px;
}

.el-table.edit-mode-spacing {
  margin-bottom: 16px;
}
</style>